<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.id" placeholder="id" style="width: 80px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.username" placeholder="username" style="width: 120px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.is_superuser" placeholder="is_superuser" style="width: 110px;" class="filter-item">
        <el-option v-for="item in superOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.profile__roles" placeholder="role" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in roleOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.profile__online" placeholder="online" style="width: 120px;" class="filter-item">
        <el-option v-for="item in onlineOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.is_active" placeholder="is_active" style="width: 120px;" class="filter-item">
        <el-option v-for="item in activeOptions" :key="item" :label="item" :value="item" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="primary" :disabled="initialRole==='admin'?false:true" @click="handleCreate">
        新增用户
      </el-button>

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="username" width="115">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="is_superuser" width="120">
        <template slot-scope="{row}">
          <span>{{ row.is_superuser }}</span>
        </template>
      </el-table-column>

      <el-table-column width="115" align="center" label="roles">
        <template slot-scope="{row}">
          <span>{{ row.profile__roles }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="online" width="90">
        <template slot-scope="{row}">
          <span>{{ row.profile__online }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180" align="center" label="email">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column width="170" align="center" label="phone">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="is_active" width="110">
        <template slot-scope="{row}">
          <span>{{ row.is_active }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="last_login" width="215">
        <template slot-scope="{row}">
          <span>{{ row.last_login }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="introduction" width="180">
        <template slot-scope="{row}">
          <span>{{ row.profile__introduction }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="208" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" :disabled="initialRole==='admin'?false:true" @click="handleUpdate(row)">
            编辑
          </el-button>
          <!--          <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">-->
          <!--            查看-->
          <!--          </el-button>-->
          <el-popover v-model="visible" placement="top" width="160">
            <p>是否确定要删除该用户的信息？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visible = false">取消</el-button>
              <el-button type="primary" size="mini" @click="visible = false, handleDelete(row,$index)">确定</el-button>
            </div>
            <el-button v-if="row.status!=='deleted'" slot="reference" size="mini" type="danger" :disabled="initialRole==='admin'?false:true">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormCreateVisible">
      <el-form ref="creatTempForm" :rules="rules" :model="creatTemp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="username" label-width="20">
          <el-input v-model="creatTemp.username" minlength="5" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item label="密码" prop="pass" label-width="20">
          <el-input v-model="creatTemp.password" type="password" auto-complete="off" minlength="5" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass" label-width="20">
          <el-input v-model="creatTemp.checkPass" type="password" auto-complete="off" minlength="5" maxlength="10" show-word-limit />
        </el-form-item>
        <a>权限等级</a>
        <el-select v-model="creatTemp.role" label="权限等级" placeholder="role" clearable style="width: 90px" class="filter-item">
          <el-option v-for="item in roleOptions" :key="item" :label="item" :value="item" />
        </el-select>
        <el-form-item label="email" prop="email" label-width="20">
          <el-input v-model="creatTemp.email" />
        </el-form-item>
        <el-form-item label="phone" prop="phone" label-width="20">
          <el-input v-model="creatTemp.phone" />
        </el-form-item>
        <el-form-item label="简介" prop="introduction" label-width="140">
          <el-input v-model="creatTemp.introduction" type="textarea" minlength="5" maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser()">
          确认
        </el-button>
        <el-button @click="resetCreateForm('creatTempForm')">
          重置
        </el-button>
        <el-button @click="dialogFormCreateVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="Id" prop="id" label-width="140">
          <el-input v-model="temp.id" :disabled="true" />
        </el-form-item>

        <el-form-item label="username" prop="username" label-width="140">
          <el-input v-model="temp.username" minlength="5" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item label="email" prop="email" label-width="140">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="phone" prop="phone" label-width="140">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="introduction" prop="introduction" label-width="140">
          <el-input v-model="temp.introduction" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus===updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getToken } from '@/utils/auth'
import { createUser, deleteRole, getRoleManage, modifyInfo } from '@/api/role'
import { getRole } from '@/api/user'

export default {
  name: 'RoleManage',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.creatTemp.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.creatTemp.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        token: getToken(),
        page: 1,
        limit: 30,
        id: undefined,
        username: undefined,
        is_superuser: undefined,
        profile__roles: undefined,
        profile__online: undefined,
        email: undefined,
        phone: undefined,
        last_login: undefined,
        is_active: undefined,
        sort: 'id'
      },
      initialRole: '3',
      roleOptions: ['admin', 1, 2, 3],
      superOptions: ['True', 'False'],
      onlineOptions: [0, 1],
      activeOptions: [0, 1],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        username: undefined,
        email: undefined,
        phone: undefined,
        introduction: undefined
      },
      creatTemp: {
        username: '',
        password: '',
        checkPass: '',
        email: '',
        phone: undefined,
        role: '',
        introduction: ''
      },
      dialogFormVisible: false,
      dialogFormCreateVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }],
        pass: [{ required: true, validator: validatePass, trigger: 'blur' }],
        checkPass: [{ required: true, validator: validatePass2, trigger: 'blur' }],
        username: [{ required: true }],
        role: [{ required: true }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.getNowRole()
  },
  methods: {
    getNowRole() {
      getRole(getToken()).then(response => {
        this.initialRole = response.role
        console.log(this.initialRole)
      })
    },
    getList() {
      this.listLoading = true
      getRoleManage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = 'id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    restCreateTemp() {
      this.creatTemp = {
        username: '',
        password: '',
        checkPass: '',
        email: '',
        role: '',
        introduction: ''
      }
    },
    handleCreate() {
      this.restCreateTemp()
      this.dialogStatus = 'create'
      this.dialogFormCreateVisible = true
      // this.$nextTick(() => {
      //   this.$refs['creatTempForm'].clearValidate()
      // })
    },
    addUser() {
      const tempData = Object.assign({}, this.creatTemp)
      console.log(tempData)
      createUser(getToken(), tempData).then(response => {
        this.list.unshift(this.creatTemp)
        this.dialogFormCreateVisible = true
        const code = response.code
        if (code === 2000) {
          this.dialogFormCreateVisible = false
          this.$notify({
            title: 'Success',
            message: response.message,
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: 'UnSuccess',
            message: response.message,
            type: 'error',
            duration: 1000
          })
        }
      })
      // this.$refs['creatTempForm'].validate((valid) => {
      //   if (valid) {
      //     const tempData = Object.assign({}, this.creatTemp)
      //     console.log(tempData)
      //     createUser(getToken(), tempData).then(response => {
      //       this.list.unshift(this.creatTemp)
      //       this.dialogFormVisible = true
      //       const code = response.code
      //       if (code === 2000) {
      //         this.dialogFormVisible = false
      //         this.$notify({
      //           title: 'Success',
      //           message: response.message,
      //           type: 'success',
      //           duration: 2000
      //         })
      //       }
      //     })
      //   }
      // })
    },
    resetCreateForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          modifyInfo(getToken(), tempData).then(response => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            const code = response.code
            if (code === 2000) {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: response.message,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: 'UnSuccess',
                message: response.message,
                type: 'error',
                duration: 1000
              })
            }
          })
        }
      })
    },
    handleDelete(row, index) {
      const tempData = Object.assign({})
      tempData.id = row.id
      deleteRole(getToken(), tempData).then(response => {
        // eslint-disable-next-line no-unused-vars
        const code = response.code
        if (code === 2000) {
          this.$notify({
            title: 'Success',
            message: response.message,
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        } else {
          this.$notify({
            title: 'UnSuccess',
            message: response.message,
            type: 'error',
            duration: 2000
          })
          this.list.splice(index, 1)
        }
      })
    },
    // handleFetchPv(pv) {
    //   fetchPv(pv).then(response => {
    //     this.pvData = response.data.pvData
    //     this.dialogPvVisible = true
    //   })
    // },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
